package owg.util.data;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class PFieldSingle<T extends PFieldElement> extends PFieldAbstract<T>
{
	T value;
	
	public PFieldSingle(PFieldOwner<? super T>  owner, Class<T> childType)
	{
		super(owner, childType);
	}
	
	@Override
	public int getMinimumSize()
	{
		return 1;
	}
	@Override
	public int getMaximumSize()
	{
		return 1;
	}
	
	@Override
	public T clr(int index) {
		throw new IllegalArgumentException("Cannot clear non-optional element");
	}
	@Override
	public int indexOf(Object n)
	{
		return value == n ? 0:-1;
	}
	
	@Override
	public int size()
	{
		return value == null?0:1;
	}
	
	@Override
	public T get(int index)
	{
		if(index < 0 || index > 1)
			throw new IllegalArgumentException("Index out of bounds: "+index+"/1");
		return value;
	}
	
	@Override
	public void set(int index, T child, Object exclude, boolean fireEvents) throws IllegalArgumentException
	{
		checkVetos(exclude, child, index);
		if(index < 0 || index >= 1)
			throw new IllegalArgumentException("Index out of bounds: "+index+"/1");
		T rem = this.value;
		this.value = child;
		if(rem != null)
			rem.removeNotify(this);
		child.addNotify(this);
		if(fireEvents)
			fireEvents(index, rem, child, exclude);
	}
	@Override
	public T remove(int index, Object exclude, boolean fireEvents) throws IllegalArgumentException
	{
		throw new IllegalArgumentException(this+" is not an optional field and the value cannot be removed.");
	}	
	
	@Override
	public String toString()
	{
		return "Single "+type.getSimpleName()+" on "+getOwner();
	}
	
	
	@Override
	public Iterator<T> iterator()
	{
		return new Iterator<T>()
			{
			boolean remaining = true;
			@Override
			public boolean hasNext()
			{
				return remaining;
			}
			
			@Override
			public T next()
			{
				if(remaining)
				{
					remaining = false;
					return get();
				}
				throw new NoSuchElementException(this+" only has one element.");
			}
			};
	}
}
